package jy.service.impl;

import java.util.HashMap;
import java.util.Map;

import jy.dao.UserDaoI;
import jy.model.User;
import jy.pageModel.PUser;
import jy.service.StoreServiceI;
import jy.service.UserServiceI;
import jy.util.MD5Util;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserServiceI {

	@Autowired
	private UserDaoI userDao;
	@Autowired
	private StoreServiceI storeService;

	@Override
	public PUser login(PUser user) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mail", user.getMail());
		//params.put("password", MD5Util.md5(user.getPassword()));
		params.put("password", MD5Util.md5(user.getPassword()));
		User t = userDao.get("from User t where t.mail = :mail and t.password = :password", params);
		if (t != null) {
			System.out.println("hehe");
			BeanUtils.copyProperties(t, user);
			return user;
		}
		return null;
	}

	@Override
	synchronized public void reg(PUser user) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("pname", user.getPname());
		if (userDao.count("select count(*) from User t where t.pname = :pname", params) > 0) {
			throw new Exception("登录名已存在！");
		} else {
			User u = new User();
			u.setPname(user.getPname());
			u.setPassword(MD5Util.md5(user.getPassword()));
			u.setMail(user.getMail());
			u.setCity(user.getCity());
			u.setArea(user.getArea());
			System.out.println(user.getTel());
			u.setTel(user.getTel());
			u.setType(1);
			userDao.save(u);
		}
	}

	@Override
	public PUser get(Integer id) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		User t = userDao.get("select t from User t  where t.id = :id", params);
		PUser u = new PUser();
		BeanUtils.copyProperties(t, u);

		return u;
	}

	@Override
	public void shopreg(PUser user) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("pname", user.getPname());
		params.put("mail", user.getMail());
		if (userDao.count("select count(*) from User t where t.pname = :pname or t.mail = :mail", params) > 0) {
			throw new Exception("登录名或邮箱已存在！");
		}/*else if (userDao.count("select count(*) from User t where t.mail = :mail", params) > 0) {
			throw new Exception("邮箱已存在！");
		}*/
		else {
			User u = new User();
			u.setPname(user.getPname());
			u.setPassword(MD5Util.md5(user.getPassword()));
			u.setMail(user.getMail());
			u.setCity(user.getCity());
			u.setArea(user.getArea());
			u.setTel(user.getTel());
			u.setType(2);//商家
			userDao.save(u);
			System.out.println("1OK");
			storeService.shopreg(user,u);
		}
	}
	


}
